﻿using log4net.Repository.Hierarchy;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI.WebControls;
using UFIDA.U9.Base.BaseBE.BaseCommon;
using UFIDA.U9C.Cust.ZL.API.DTO.SRMDTO;
using UFSoft.UBF.Service;

namespace UFIDA.U9C.Cust.ZL.API.Utils
{
    public class RequestHelper
    {
        //private string AuthURL { get; set; }
        private string User { get; set; }
        private string Password { get; set; }

        //log4net.ILog logger = log4net.LogManager.GetLogger("UFIDA.U9C.Cust.ZL.API.Utils.Request");
        log4net.ILog logger = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        public RequestHelper(string user, string password)
        {
            //AuthURL = authURL;
            User = user;
            Password = password;
        }
        public RequestHelper(string user, string password,log4net.ILog log)
        {
            //AuthURL = authURL;
            User = user;
            Password = password;
            this.logger = log;
        }

        public POReturnDTO PostWebRequest(string Url, string Data)
        {
            string retString = "";

            POReturnDTO ret = new POReturnDTO();
            logger.Error(string.Format("调用接口：{0}，\r\n请求值：\r\n {1}", Url, Data));

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            string authInfo = Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(User + ":" + Password));
            request.Headers["Authorization"] = "Basic " + authInfo;
            request.Method = "POST";
            byte[] bytes = Encoding.UTF8.GetBytes(Data);
            request.ContentType = "application/json";
            request.ContentLength = bytes.Length;
            Stream myResponseStream = request.GetRequestStream();
            myResponseStream.Write(bytes, 0, bytes.Length);

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            retString = myStreamReader.ReadToEnd();

            myStreamReader.Close();
            myResponseStream.Close();

            if (response != null)
            {
                response.Close();
            }
            if (request != null)
            {
                request.Abort();
            }
            logger.Info(string.Format("调用接口：{0}，返回信息：\r\n{1}", Url, retString));
            ret = BaseJsonHelper.JsonDeserializeJS<POReturnDTO>(retString);
            return ret;
        }

        /// <summary>
        /// 异步请求  
        /// </summary>
        /// <param name="url"></param>
        /// <param name="body"></param>
        /// <returns></returns>
        public ReturnDTO PostRequest(string url, string body)
        {

            ReturnDTO ret = new ReturnDTO();
            HttpClient client = new HttpClient();
            //BasicAuthenticationHeaderValue basicAuthentication = new BasicAuthenticationHeaderValue(User, Password);
            //AuthenticationHeaderValue authentication = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{User}:{Password}")));
            client.DefaultRequestHeaders.Authorization = new BasicAuthenticationHeaderValue(User, Password); //basicAuthentication;

            StringContent postContent = new StringContent(body, Encoding.UTF8);
            postContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            logger.Error(url +"\r\n"+ body);
            client.PostAsync(url, postContent).ContinueWith((postTask) =>
            {
                HttpResponseMessage response = postTask.Result;
                // 确认响应成功，否则抛出异常
                response.EnsureSuccessStatusCode();
                // 异步读取响应为字符串
                response.Content.ReadAsStringAsync().ContinueWith((readTask) =>
                {
                    logger.Error($"请求返回的信息:{BaseJsonHelper.GetJson(readTask)}");
                    ret = BaseJsonHelper.JsonDeserializeJS<ReturnDTO>(readTask.Result);
                }).Wait();
                
            }).Wait();



            return ret;



        }

        public string Post(string url, string body)
        {

            //ReturnDTO ret = new ReturnDTO();
            string ret = string.Empty;
            HttpClient client = new HttpClient();
            //BasicAuthenticationHeaderValue basicAuthentication = new BasicAuthenticationHeaderValue(User, Password);
            //AuthenticationHeaderValue authentication = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{User}:{Password}")));
            client.DefaultRequestHeaders.Authorization = new BasicAuthenticationHeaderValue(User, Password); //basicAuthentication;

            StringContent postContent = new StringContent(body, Encoding.UTF8);
            postContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            logger.Info(url + body);
            client.PostAsync(url, postContent).ContinueWith((postTask) =>
            {


                HttpResponseMessage response = postTask.Result;
                // 确认响应成功，否则抛出异常
                response.EnsureSuccessStatusCode();
                // 异步读取响应为字符串
                response.Content.ReadAsStringAsync().ContinueWith((readTask) =>
                {
                    ret = readTask.Result;
                }).Wait();

            }).Wait();


            return ret;



        }

        /// <summary>
        /// HTTP Basic Authentication authorization header
        /// </summary>
        /// <seealso cref="System.Net.Http.Headers.AuthenticationHeaderValue" />
        public class BasicAuthenticationHeaderValue : AuthenticationHeaderValue
        {
            /// <summary>
            /// Initializes a new instance of the <see cref="BasicAuthenticationHeaderValue"/> class.
            /// </summary>
            /// <param name="userName">Name of the user.</param>
            /// <param name="password">The password.</param>
            public BasicAuthenticationHeaderValue(string userName, string password)
                : base("Basic", EncodeCredential(userName, password))
            { }

            /// <summary>
            /// Encodes the credential.
            /// </summary>
            /// <param name="userName">Name of the user.</param>
            /// <param name="password">The password.</param>
            /// <returns></returns>
            /// <exception cref="ArgumentNullException">userName</exception>
            public static string EncodeCredential(string userName, string password)
            {
                if (string.IsNullOrWhiteSpace(userName)) throw new ArgumentNullException(nameof(userName));
                if (password == null) password = "";

                Encoding encoding = Encoding.UTF8;
                string credential = String.Format("{0}:{1}", userName, password);

                return Convert.ToBase64String(encoding.GetBytes(credential));
            }
        }



    }
}
